<?php

namespace App\Http\Controllers\Saas;

use App\Http\Config\ErrorCode;
use App\Library\Tools;
use App\Models\Saas\Mall;
use App\Models\Saas\UserManager;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/** 后台管理员管理 */
class ManagerController extends BaseController
{
    private $field = [
        "username" => "require", "password" => "require", "expired_time" => null, "app_count" => null, "remark" => null, "mobile" => "require"
    ]; //填入数据库需要存储的表字段
    private $fieldMsg = [
        "username" => "用户名", "password" => "密码", "expired_time" => "有效期", "app_count" => "小程序数量", "remark" => "备注", "mobile" => "手机号"
    ];
    private $data = [];

    // 账户列表
    public function getAccountList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $page = isset($request['page']) ? $request['page'] : 1;
        $pageSize = isset($request['pageSize']) ? $request['pageSize'] : 10;
        //搜索条件
        $filter = function ($query) use($request){
            $query->where("status", "<>", 3);
            if(!$this->is_su){ // 不是超管，只显示自己的账号列表
                $query->where("id", "=", $this->AU["id"]);
            }
            if(!empty($request['search'])){
                $query->whereRaw("`username` like '%{$request["search"]}%' or `mobile` like '%{$request["search"]}%'");
            }
        };
        $data = UserManager::getList("id,username,remark,expired_time,app_count,mobile", $filter, $page, $pageSize);
        if($data["list"]){
            foreach ($data['list'] as &$item){
                $item["createCount"] = Mall::query()->where(["manager_id" => $item["id"]])->count();
                if(!is_numeric($item["appCount"])){
                    $item["canCreate"] = "无限制";
                }else{
                    $item["canCreate"] = $item["appCount"] > $item["createCount"] ? $item["appCount"] - $item["createCount"] : 0;
                }
                $item["expiredTime"] = empty(trim($item["expiredTime"])) ? "永久" : date("Y-m-d", $item["expiredTime"]);
            }
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 管理员基本信息
    public function getInfo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['id'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "账户ID"));
        }
        if(!$this->is_su && $request['id'] != $this->AU["id"]){
            return $this->return_result(ErrorCode::code("customized", "您无权限操作"));
        }
        $data = UserManager::query()->select(explode(",", "id,username,remark,expired_time,app_count,mobile"))
            ->where("id", $request['id'])
            ->first();
        if($data){
            $data = Tools::transferFields($data->toArray());
            if(!empty($data["expiredTime"])){
                $data["expiredTime"] = date("Y-m-d", $data["expiredTime"]);
            }
            $this->returnData["data"] = $data;
        }else{
            $this->returnData["data"] = [];
        }
        return $this->return_result($this->returnData);
    }

    // 所有管理员
    public function getAll(){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $data = UserManager::query()->where("status", '=', 1)->select(["id", "username"])->get();
        if($data){
            $data = Tools::transferFields($data->toArray());
            $this->returnData["data"] = $data;
        }else{
            $this->returnData["data"] = [];
        }
        return $this->return_result($this->returnData);
    }

    // 更新账户信息
    public function doUpdate(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['id'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "账户ID"));
        }
        if(!$this->is_su && $request["id"] != $this->AU["id"]){
            return $this->return_result(ErrorCode::code("customized", "您无权限操作"));
        }
        unset($this->field["username"], $this->field["password"]);
        foreach ($this->field as $k => $v) {
            $ks = Str::camel($k); //转换字段，变驼峰
            if ($v === 'require' && !isset($request[$ks])) {
                return $this->return_result(ErrorCode::code("params_not_exist", $this->fieldMsg[$k]));
            }
            $this->data[$k] = isset($request[$ks]) ? trim($request[$ks]) : $v;
        }
        if(!preg_match('/^1[3456789]\d{9}$/', $request["mobile"])){
            return $this->return_result(ErrorCode::code("customized", "手机号错误"));
        }
        $userData = UserManager::query()->where("id", $request["id"])->select(["type"])->first()->toArray();
        if(!$userData){
            return $this->return_result(ErrorCode::code("customized", "账户不存在"));
        }
        if(UserManager::query()->where("id", "<>", $request["id"])->where("mobile", $this->data["mobile"])->count()){
            return $this->return_result(ErrorCode::code("customized", "手机号已存在"));
        }
        if($userData["type"] == '2'){ // 由其它系统创建的账号不允许修改
            unset($this->data["expired_time"]);
        }else {
            $this->data["expired_time"] = !is_numeric($this->data["expired_time"]) ? strtotime($this->data["expired_time"]) : $this->data["expired_time"];
        }
        $res = UserManager::query()->where("id", $request["id"])->update($this->data);
        if($res || $res === 0){
            $this->returnData["msg"] = "更新账户成功";
        }else{
            $this->returnData = ErrorCode::code("customized", "更新账户失败");
        }
        return $this->return_result($this->returnData);
    }

    // 添加账户
    public function doAdd(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$this->is_su){
            return $this->return_result(ErrorCode::code("customized", "您无权限操作"));
        }
        foreach ($this->field as $k => $v) {
            $ks = Str::camel($k); //转换字段，变驼峰
            if ($v === 'require' && !isset($request[$ks])) {
                return $this->return_result(ErrorCode::code("params_not_exist", $this->fieldMsg[$k]));
            }
            $this->data[$k] = isset($request[$ks]) ? trim($request[$ks]) : $v;
        }
        if(!preg_match('/^1[3456789]\d{9}$/', $request["mobile"])){
            return $this->return_result(ErrorCode::code("customized", "手机号错误"));
        }
        if(UserManager::query()->where("username", $this->data["username"])->count()){
            return $this->return_result(ErrorCode::code("customized", "账号已存在"));
        }
        if(UserManager::query()->where("mobile", $this->data["mobile"])->count()){
            return $this->return_result(ErrorCode::code("customized", "手机已存在"));
        }
        $this->data["type"] = 1;
        $this->data["password"] = bcrypt($this->data["password"]);
        $this->data["expired_time"] = $this->data["expired_time"] && !is_numeric($this->data["expired_time"]) ? strtotime($this->data["expired_time"]) : $this->data["expired_time"];
        if(!UserManager::query()->insert($this->data)){
            $this->returnData = ErrorCode::code("customized", "添加账户失败");
        }
        return $this->return_result($this->returnData);
    }

    // 修改密码
    public function doModifyPwd(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['id'])){
            $request['id'] = $this->AU["id"];
        }
        if(empty($request['password'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "新密码"));
        }
        if(empty($request['confirmPassword'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "确认密码"));
        }
        if($request['password'] != $request['confirmPassword']){
            return $this->return_result(ErrorCode::code("customized", "确认密码不一致"));
        }
        if(!$this->is_su && $request["id"] != $this->AU["id"]){
            return $this->return_result(ErrorCode::code("customized", "您无权限操作"));
        }
        $this->data["password"] = bcrypt(trim($request['password']));
        $res = UserManager::query()->where("id", $request["id"])->update($this->data);
        if($res || $res === 0){
            $this->returnData["msg"] = "修改密码成功";
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "修改密码失败";
        }
        return $this->return_result($this->returnData);
    }

    // 修改手机号
    public function doModifyMobile(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$this->is_su && $request["id"] != $this->AU["id"]){
            return $this->return_result(ErrorCode::code("customized", "您无权限操作"));
        }
        if(empty($request['id'])){
            $request['id'] = $this->AU["id"];
        }
        if(empty($request['mobile'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "新手机号"));
        }
        if(empty($request['code'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "短信验证码"));
        }
        if(!preg_match('/^1[3456789]\d{9}$/', $request["mobile"])){
            return $this->return_result(ErrorCode::code("customized", "手机号错误"));
        }
        if(UserManager::query()->where("id", "<>", $request["id"])->where("mobile", $request["mobile"])->count()){
            return $this->return_result(ErrorCode::code("customized", "手机号已存在"));
        }
        $request["mobile"] = trim($request["mobile"]);
        $res = DB::table('verification')->where('mobile', $request["mobile"])->where("overdue_time", ">", time())->select(["code", "id", 'overdue_time'])->first();
        $res = json_decode(json_encode($res),true);
        if ($res['overdue_time'] < time()){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData['msg'] = '验证码过期';
            return $this->return_result($this->returnData);
        }
        if ($res['code'] != $request["code"]){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData['msg'] = '验证码错误';
            return $this->return_result($this->returnData);
        }
        DB::table('verification')->where('id', $res["id"])->update(["overdue_time" => time()]);
        if(UserManager::query()->where("id", $request["id"])->update(["mobile" => $request["mobile"]])){
            $this->returnData["msg"] = "修改手机号成功";
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "修改手机号失败";
        }
        return $this->return_result($this->returnData);
    }

    // 删除
    public function doDelete(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(empty($request['id'])){
            return $this->return_result(ErrorCode::code("params_not_exist", "账户ID"));
        }
        if($this->is_su && $request["id"] == $this->AU["id"]){
            return $this->return_result(ErrorCode::code("customized", "不能删除超管账户"));
        }
        if(!$this->is_su && $request["id"] != $this->AU["id"]){
            return $this->return_result(ErrorCode::code("customized", "您无权限操作"));
        }
        if(UserManager::query()->where("id", $request["id"])->delete()){
            $this->returnData["msg"] = "删除成功";
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "删除失败";
        }
        return $this->return_result($this->returnData);
    }
}